-module(foo_proc).
-export([process/0, 
         process/1]).

-define(LINE_PATTERN, "^\\s+\\d+\\.").

-record(team, 
        {team_name, fscore, ascore}).

%% 判断是否为数据行
is_data_line(Line) ->
    {ok, Re} = re:compile(?LINE_PATTERN),
    case re:run(Line, Re) of
        {match, _Captured} ->true;
        nomatch -> false 
    end.

%% 解析一行返回一个tuple
line_parser(Line) ->

    Team = string:sub_word(Line, 2),
    FScore = list_to_integer(string:sub_word(Line, 7)),
    AScore = list_to_integer(string:sub_word(Line, 9)),

    #team{team_name=Team, 
          fscore=FScore, 
          ascore=AScore}.

%% 排序谓词
sort_pred(#team{fscore=FScore1, ascore=AScore1}, 
          #team{fscore=FScore2, ascore=AScore2}) -> 
    abs(FScore1 - AScore1) < abs(FScore2 - AScore2). 

process() ->
    process("football.dat").

process(FileName) ->

    Result = file_common:process(FileName,
                                 fun sort_pred/2,
                                 fun is_data_line/1,
                                 fun line_parser/1),

    io:format("~p~n", [Result#team.team_name]).

